/**
 * @file 权限管理
 * @date 2025/11/12 20:19:32
 * @author lyqjob@yeah.net
 */


import {  useState, useEffect  } from 'react';
import { Table, Tag, Space, Button, Modal, Form, Input, Select, Col, Row, message, Tooltip, Radio } from 'antd';
import AuthButton from '@/components/AuthButton';

import { adminApi } from "@/services/admin";
import dayjs from '@/utils/dayjs.js';



const PermissionList = () => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true)
    const [form] = Form.useForm();
    const [open, setOpen] = useState(false);
    const [formValues, setFormValues] = useState({});
    const [pageSize, setPageSize] = useState(10)
    const [current, setCurrent] = useState(1)
    const [total, setTotal] = useState(0)
    const [permissionType, setPermissionType] = useState(1)
    const [menuPermissions, setMenuPermissions] = useState([])
    const [selectedRowKeys, setSelectedRowKeys] = useState([])

    // 获取操作类型的显示标签
    const getOperationTypeTag = (type) => {
        const tagMap = {
            'query': <Tag color="blue">查询</Tag>,
            'create': <Tag color="green">新增</Tag>,
            'update': <Tag color="orange">修改</Tag>,
            'delete': <Tag color="red">删除</Tag>,
            'export': <Tag color="purple">导出</Tag>,
            'import': <Tag color="cyan">导入</Tag>,
            'other': <Tag color="default">其他</Tag>
        };
        return tagMap[type] || <Tag color="default">未知</Tag>;
    };

    // 表格列配置
    const columns = [
        {
            title: '编码',
            dataIndex: 'code',
            key: 'code',
            ellipsis: true,
            width: 150,
            fixed: 'left',
        },
        {
            title: '系统预制', dataIndex: 'is_system', key: '', width: 100,
            render: (tag) => {
                return (
                    <Tag color={tag === 1 ? 'gold' : 'green'} key={tag}>
                        {tag === 1 ? '是' : '否'}
                    </Tag>
                )
            }
        },
        {
            title: '权限名称',
            dataIndex: 'permission_name',
            key: 'permission_name',
            ellipsis: true,

            width: 150,
            render: (text) => <Tooltip title={text}>{text}</Tooltip>
        },
        {
            title: '权限编码',
            dataIndex: 'permission_code',
            key: 'permission_code',
            ellipsis: true,
            width: 150,
            // render: (text,record) => record.module_code + ':' + text
        },
        {
            title: '模块编码',
            dataIndex: 'module_code',
            key: 'module_code',
            ellipsis: true,
            width: 100,
        },
        {
            title: '操作类型',
            dataIndex: 'operation_type',
            key: 'operation_type',
            width: 100,
            render: (type) => getOperationTypeTag(type)
        },
        // {
        //   title: '权限类型',
        //   dataIndex: 'permission_type',
        //   key: 'permission_type',
        //   render: (type) => (
        //     <Tag color={type === 1 ? 'green' : 'red'}>
        //       {type === 1 ? '菜单页面' : 'API接口'}
        //     </Tag>
        //   )
        // },
        {
            title: 'API路径',
            dataIndex: 'api_path',
            key: 'api_path',
            ellipsis: true,
            width: 200,
        },
        {
            title: 'API方法',
            dataIndex: 'api_method',
            key: 'api_method',
            width: 100,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 100,
            render: (status) => (
                <Tag color={status === 1 ? 'green' : 'red'}>
                    {status === 1 ? '启用' : '禁用'}
                </Tag>
            )
        },
        {
            title: '描述',
            dataIndex: 'description',
            key: 'description',
            ellipsis: true,
            width: 200,
            render: (text) => text || '-'
        },
        {
            title: '创建时间',
            dataIndex: 'created_at',
            key: 'created_at',
            ellipsis: true,
            width: 200,
            render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss') || '-'
        },
        {
            title: '创建人',
            dataIndex: 'create_by_name',
            key: 'create_by_name',
            ellipsis: true,
            width: 150,
        },
        {
            title: '更新时间',
            dataIndex: 'updated_at',
            key: 'updated_at',
            ellipsis: true,
            width: 200,
            render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss') || '-'
        },
        {
            title: '更新人',
            dataIndex: 'update_by_name',
            key: 'update_by_name',
            ellipsis: true,
            width: 150,
        },
        {
            title: '操作',
            key: 'action',
            width: 150,
            fixed: 'right',
            render: (_, record) => (
                <Space>
                    {record.is_system === 0 &&
                        <AuthButton permission={['permission:update']}>
                            <Button type="link" onClick={() => handleUpdate(record)}>
                                编辑
                            </Button>
                        </AuthButton>
                    }
                    {record.is_system === 0 &&
                        <AuthButton permission={['permission:delete']}>
                            <Button type="link" danger onClick={() => handleDelete(record.id)}>
                                删除
                            </Button>
                        </AuthButton>
                    }
                </Space>
            )
        }
    ];




    useEffect(() => {
        getList(current, pageSize)
        getMenuPermissions()
    }, [])

    // 获取全部菜单页面
    const getMenuPermissions = async () => {
        const [err, res] = await adminApi.getAllMenuList({ page: 1, limit: 1000, node_type: 2 })
        if (err) {
            // message.warning('获取菜单权限列表失败')
            return
        }
        if (res?.code === 200 && res?.data) {
            setMenuPermissions(res.data)
        }
    }

    // 编辑权限
    const handleUpdate = (record) => {
        const values = Object.assign({}, record);
        const permission_code = values.permission_code;
        if (permission_code) {
            values.permission_code = values.permission_code.split(':')[1]
        }
        setFormValues(values)
        form.setFieldsValue(values)
        setOpen(true)
    }

    // 获取权限列表
    const getList = async (page, limit) => {

        const [err, res] = await adminApi.getPermissions({ page, limit });
        if (err) {
            setLoading(false)
            // message.warning('获取日志列表失败')
            return
        }
        if (res?.code === 200 && res?.data?.data) {
            setLoading(false)
            setData(res.data.data)
            setTotal(res.data.pagination.total)
            window.process.done();
        }

    }

    // 创建或更新权限
    const onCreate = async values => {
        if (values.module_code && values.permission_code) {
            values.permission_code = values.module_code + ':' + values.permission_code
        }
        // 编辑
        if (formValues?.id) {
            values.id = formValues.id
            const [err, res] = await adminApi.updatePermission(values)
            if (err) {
                // message.warning('添加失败')
                // setOpen(false)
            }
            if (res) {
                message.success('更新成功')
                form.resetFields()
                setOpen(false)
                getList(current, pageSize)
            }
            return
        }

        const [err, res] = await adminApi.createPermission(values)
        if (err) {
            // message.warning('添加失败')
            // setOpen(false)
        }
        if (res) {
            message.success('添加成功')
            form.resetFields()
            setOpen(false)
            getList(current, pageSize)
        }

    };


    // 删除权限
    const handleDelete = async (id) => {
        const [err, res] = await adminApi.deletePermission(id)
        if (err) {
            // message.warning('删除失败')
            return
        }
        if (res) {
            message.success('删除成功')
            getList(current, pageSize)
        }
    }

    // 批量删除权限
    const handleBatchDelete = async (values) => {
        if (values.length === 0) {
            message.warning('请选择要删除的用户')
            return
        }
        const [err, res] = await adminApi.batchDeletePermission({ ids: values })
        if (err) {
            // message.warning('批量删除失败')
            return
        }
        if (res) {
            message.success('批量删除成功')
            setSelectedRowKeys([])
            getList(current, pageSize)
        }
    }


    // 切换权限类型
    const changeRadio = (e) => {
        setPermissionType(e.target.value)
        form.setFieldsValue({ permission_type: e.target.value })
    }


    // 分页
    const rowSelection = {
        onChange: (newSelectedRowKeys, _selectedRows) => {
            setSelectedRowKeys(newSelectedRowKeys);
        },
        getCheckboxProps: record => ({
            disabled: record.name === '超级管理员', // Column configuration not to be checked
        }),
    };

    return (
        <div className="container">
            <Space>
                <AuthButton permission={['permission:create']}>
                    <Button onClick={() => { setOpen(true) }} type="primary" style={{ marginBottom: 16 }}>
                        新增
                    </Button>
                </AuthButton>
                <AuthButton permission={['permission:batch:delete']}>
                    <Button onClick={() => { handleBatchDelete(selectedRowKeys) }} type="primary" danger style={{ marginBottom: 16 }}>
                        批量删除
                    </Button>
                </AuthButton>





            </Space>
            <Table
                loading={loading}
                rowKey={'id'}
                columns={columns}
                rowSelection={rowSelection}
                dataSource={data}
                scroll={{
                    x: 1500,
                    y: 400
                }}
                pagination={{
                    pageSize,
                    current,
                    showPage: true,
                    total: total,
                    showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 条`,
                    onChange: (page, pageSize) => {
                        setPageSize(pageSize)
                        setCurrent(page)
                        getList(page, pageSize)
                    }
                }}
            />

            <Modal
                open={open}
                title={formValues?.id ? '编辑权限' : '新增权限'}
                okText="确定"
                cancelText="取消"
                width={800}
                okButtonProps={{ autoFocus: true, htmlType: 'submit' }}
                onCancel={() => {
                    setOpen(false)
                    setFormValues()
                }}
                destroyOnHidden
                modalRender={dom => (
                    <Form
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        layout="horizontal"
                        form={form}
                        name="form_in_modal"
                        initialValues={{ permission_type: 1 }}
                        clearOnDestroy
                        onFinish={values => onCreate(values)}
                        style={{ maxWidth: 800 }}

                    >
                        {dom}
                    </Form>
                )}
            >
                <Form.Item
                    name="permission_type"
                    label="权限类型"
                    hidden
                    rules={[{ required: true, message: '请选择权限类型' }]}
                >
                    <Radio.Group onChange={changeRadio} disabled={parent.id? true : false}>
                        <Radio value={1}>按钮</Radio>
                        <Radio value={2}>API</Radio>
                    </Radio.Group>
                </Form.Item>
                <Row gutter={16}>
                    <Col span={8}>
                        <Form.Item
                            name="menu_id"
                            label="关联菜单ID"
                            hidden

                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            name="module_code"
                            label="所属模块"
                            placeholder="请选择所属模块"
                            rules={[{ required: true, message: '请选择所属模块' }]}
                        >
                            <Select>
                                {
                                    menuPermissions.map(item => (
                                        <Select.Option key={item.id} value={item.module_code || ''}>{item.name}</Select.Option>
                                    ))
                                }
                            </Select>
                        </Form.Item>
                    </Col>


                    <Col span={16}>
                        <Space.Compact>
                            <Form.Item
                                name="module_code"
                                label="权限编码"
                                rules={[{ required: true, message: '请选择模块编码' }]}
                            >
                                <Input disabled style={{ width: '100%', borderRight: '0 none' }} />
                            </Form.Item>
                            <Form.Item
                                name="permission_code"
                                // label="权限编码"
                                wrapperCol={{ span: 24 }}
                                rules={[{ required: true, message: '请输入权限编码' }]}
                            >
                                <Input addonBefore={':'} />
                            </Form.Item>
                        </Space.Compact>


                    </Col>


                </Row>
                <Row gutter={16}>
                    <Col span={8}>
                        <Form.Item
                            name="permission_name"
                            label="权限名称"
                            rules={[{ required: true, message: '请输入权限名称' }]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            name="operation_type"
                            label="操作类型"
                            rules={[{ required: true, message: '请选择操作类型' }]}
                        >

                            <Select>
                                <Select.Option value={'query'}>查询</Select.Option>
                                <Select.Option value={'create'}>新增</Select.Option>
                                <Select.Option value={'update'}>修改</Select.Option>
                                <Select.Option value={'delete'}>删除</Select.Option>
                                <Select.Option value={'export'}>导出</Select.Option>
                                <Select.Option value={'import'}>导入</Select.Option>
                                <Select.Option value={'other'}>其他</Select.Option>
                            </Select>
                        </Form.Item>
                    </Col>

                    <Col span={8}>
                        <Form.Item
                            name="api_method"
                            label="API方法"
                            rules={[{ required: true, message: '请输入API方法' }]}
                        >
                            <Select>
                                <Select.Option value={'GET'}>GET</Select.Option>
                                <Select.Option value={'POST'}>POST</Select.Option>
                                <Select.Option value={'PUT'}>PUT</Select.Option>
                                <Select.Option value={'DELETE'}>DELETE</Select.Option>
                            </Select>
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col span={8}>
                        <Form.Item
                            name="api_path"
                            label="API路径"
                            rules={[{ required: true, message: '请输入API路径' }]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>


                    {/* {
                        permissionType == 1 && (
                            <Col span={8}>
                                <Form.Item
                                    name="button_icon"
                                    label="按钮图标"
                                    // rules={[{ required: true, message: '请输入按钮图标' }]}
                                >
                                    <Input />
                                </Form.Item>
                            </Col>
                        )
                    } */}
                    {/* {
                        permissionType == 1 && (
                            <Col span={16}>
                                <Form.Item
                                    wrapperCol={{ span: 20 }}
                                    labelCol={{ span: 4 }}
                                    name="related_api_permissions"
                                    label="关联API"    
                                >
                                    <Select
                                        mode="multiple"
                                        placeholder="请选择关联API"
                                    >
                                        {
                                            apiPermissions.map(item => (
                                                <Select.Option key={item.id} value={item.id}>{item.permission_name}</Select.Option>
                                            ))
                                        }
                                    </Select>
                                </Form.Item>
                            </Col>
                        )
                    } */}
                    <Col span={16}>
                        <Form.Item
                            wrapperCol={{ span: 20 }}
                            labelCol={{ span: 4 }}
                            name="description"
                            label="API描述"
                            rules={[{ required: permissionType === 2, message: '请输入API描述' }]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
            </Modal>
        </div>
    )
}


export default PermissionList;
